package user

import (
	"api/common"
	"api/pb/user"
	"context"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(req *types.PasswordRequest) (resp *types.Empty, err error) {
	userID, err := common.GetUserIDFromCtx(l.ctx)
	if err != nil {
		return nil, err
	}

	_, err = l.svcCtx.UserRPC.CheckPassword(l.ctx, &user.CheckPasswordRequest{
		Id:       userID,
		Password: req.OldPassword,
	})
	if err != nil {
		return nil, err
	}

	_, err = l.svcCtx.UserRPC.UpdateUser(l.ctx, &user.UserInfo{
		Id:       userID,
		Password: req.NewPassword,
	})
	if err != nil {
		return nil, err
	}
	return &types.Empty{}, nil
}
